package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class ProgramListResponse {

	private DocumentBuilderFactory docFactory;
	private Document document;
	private Node root;

	public ProgramListResponse() {
		docFactory = DocumentBuilderFactory.newInstance();
		try {
			document = docFactory.newDocumentBuilder().newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		root = document.createElement("recommended-programs");
		document.appendChild(root);
	}

	public void addProgram(String crid, String title, String uri) {
		Element program = document.createElementNS(null, "program");
		program.setAttributeNS(null, "crid", crid);
		program.setAttributeNS(null, "uri", uri);
		program.appendChild(document.createCDATASection(title));
		root.appendChild(program);
	}

	public String toString() {
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		StringWriter res = new StringWriter();
		try {
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(res);
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		return res.toString();
	}

}
